package json.json.praseJSON;

import com.alibaba.fastjson.JSONObject;
import json.json.impl_Interface.ParseJsonInterface;
import json.json.impl_Interface.ParseJsonInterface;

import java.io.*;

public class AbstractParseJSONFile implements ParseJsonInterface {

    /**
     * 把json文件解析成String
     * @param ORIGIN_PATH json文件的路径，获取接送文件路径方法：把复制到idea里面-》选中json文件-》Ctrl+shift+c（复制json文件路径）-》把路径传给ReadFile方法
     * @return 返回json文件的string
     */

    @Override
    public  String ReadJSONFile(String ORIGIN_PATH) {
        BufferedReader reader = null;
        String laststr = "";
        try{
            FileInputStream fileInputStream = new FileInputStream(ORIGIN_PATH);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while((tempString = reader.readLine()) != null){
                laststr += tempString;
            }
            reader.close();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

    /**
     *把jsonObject写入指定路径的文件中
     * @param DESTINATION_PATH
     * @param jsonObject
     * @throws IOException
     */
    @Override
    public void WriterJsonObjectToJSONFile(String DESTINATION_PATH, JSONObject jsonObject) throws IOException {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(DESTINATION_PATH),"UTF-8");
        outputStreamWriter.write(jsonObject.toString());
        outputStreamWriter.flush();//清空缓冲区，强制输出数据
        outputStreamWriter.close();//关闭输出流
    }
}
